#include "main.h"
#include <stdio.h>
#include <stdint.h>
#include "my_uart.h"


#define countof(a) (sizeof(a) / sizeof(*(a)))



USART_InitType USART_InitStructure;
uint8_t uartz_recv_flag = 0;
uint8_t uartz_tx_buff[USARTz_MAX_BUFF_SIZE] = "123456789_USART Interrupt Example: USARTy -> USARTz using Interrupt";
uint8_t uartz_rx_buff[USARTz_MAX_BUFF_SIZE];

uint8_t uarty_tx_buff[USARTz_MAX_BUFF_SIZE] = "USART Interrupt Example: USARTz -> USARTy using Interrupt";
uint8_t uarty_rx_buff[USARTz_MAX_BUFF_SIZE];

#define TxBufferSize1 (countof(uartz_tx_buff) - 1)
#define TxBufferSize2 (countof(uarty_tx_buff) - 1)
#define RxBufferSize1 TxBufferSize2
#define RxBufferSize2 TxBufferSize1


__IO uint8_t TxCounter1         = 0x00;
__IO uint8_t TxCounter2         = 0x00;
__IO uint8_t RxCounter1         = 0x00;
__IO uint8_t RxCounter2         = 0x00;
uint8_t NbrOfDataToTransfer1    = TxBufferSize1;
uint8_t NbrOfDataToTransfer2    = TxBufferSize2;
uint8_t NbrOfDataToRead1        = RxBufferSize1;
uint8_t NbrOfDataToRead2        = RxBufferSize2;
__IO TestStatus TransferStatus1 = FAILED;
__IO TestStatus TransferStatus2 = FAILED;

static USART_InitType USART_InitStructure;

/***********************************************
 * @brief  Configures the DMA.
 **********************************************/

void uart_dma_init(void)
{
	DMA_InitType DMA_InitStructure;
	NVIC_InitType NVIC_InitStructure;
	/* 使能DMA时钟 */
	RCC_EnableAHBPeriphClk(RCC_AHB_PERIPH_DMA, ENABLE);
	/* 配置DMA USART发送通道*/
	DMA_DeInit(USARTz_Tx_DMA_Channel);
	DMA_InitStructure.PeriphAddr = (uint32_t)&(USARTz->DAT);				//外设地址
	DMA_InitStructure.MemAddr    = (uint32_t)uartz_tx_buff;	//本例程发送和接收共用一个数组，接收到数据之后立即返回
	DMA_InitStructure.Direction  = DMA_DIR_PERIPH_DST;		//外设作为目标设备
	DMA_InitStructure.BufSize    = TxBufferSize1;		//发送数据大小，每次发送可以重新定义
	DMA_InitStructure.PeriphInc      = DMA_PERIPH_INC_DISABLE;
	DMA_InitStructure.DMA_MemoryInc  = DMA_MEM_INC_ENABLE;
	DMA_InitStructure.PeriphDataSize = DMA_PERIPH_DATA_SIZE_BYTE;
	DMA_InitStructure.MemDataSize    = DMA_MemoryDataSize_Byte;
	DMA_InitStructure.CircularMode   = DMA_MODE_NORMAL;
	DMA_InitStructure.Priority       = DMA_PRIORITY_VERY_HIGH;
	DMA_InitStructure.Mem2Mem        = DMA_M2M_DISABLE;
	DMA_Init(USARTz_Tx_DMA_Channel, &DMA_InitStructure);
	DMA_RequestRemap(USARTz_Tx_DMA_REMAP, DMA, USARTz_Tx_DMA_Channel, ENABLE);
	/* 使能传输完成中断 */
	DMA_ConfigInt(USARTz_Tx_DMA_Channel, DMA_INT_TXC, ENABLE);
	
	/* 配置DMA USART接收*/
	DMA_DeInit(USARTz_Rx_DMA_Channel);
	DMA_InitStructure.PeriphAddr = (uint32_t)&(USARTz->DAT);
	DMA_InitStructure.MemAddr    = (uint32_t)uartz_rx_buff;
	DMA_InitStructure.Direction  = DMA_DIR_PERIPH_SRC;
	DMA_InitStructure.BufSize    = USARTz_MAX_BUFF_SIZE;					//默认接收数据大小
	DMA_Init(USARTz_Rx_DMA_Channel, &DMA_InitStructure);
	DMA_RequestRemap(USARTz_Rx_DMA_REMAP, DMA, USARTz_Rx_DMA_Channel, ENABLE);
	/* 使能传输完成中断 */
	DMA_ConfigInt(USARTz_Rx_DMA_Channel, DMA_INT_TXC, ENABLE);
	/* ！！！初始状态关闭发送通道，需要时打开，否则初始化完成之后会直接发送一包数据 */
	DMA_EnableChannel(USARTz_Tx_DMA_Channel, DISABLE);  
	/* 打开DMA接收通道 */
	DMA_EnableChannel(USARTz_Rx_DMA_Channel, ENABLE); 
	/*最后配置DMA相关的中断，正常如果余量足够接收中断可以不配置 */
	/* 配置DMA发送中断*/
	NVIC_InitStructure.NVIC_IRQChannel            = USARTz_Tx_DMA_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority    = 1;
	NVIC_InitStructure.NVIC_IRQChannelCmd         = ENABLE;
	NVIC_Init(&NVIC_InitStructure);
	/* 配置DMA接收中断*/
	NVIC_InitStructure.NVIC_IRQChannel            = USARTz_Rx_DMA_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority    = 2;
	NVIC_InitStructure.NVIC_IRQChannelCmd         = ENABLE;
	NVIC_Init(&NVIC_InitStructure);
}


/*使用DMA发送数据，数据为usartx_rx_buf内存储的数据
  uint16_t Length 要发送的数据长度, 已经指定输出buff为 uartz_tx_buff[]
*/
void uartx_send_data(uint8_t *p_buff, uint16_t len)
{
#ifdef UART_USE_DMA
	DMA_EnableChannel(USARTz_Tx_DMA_Channel, DISABLE);	  //关闭DMA通道	 
	DMA_SetCurrDataCounter(USARTz_Tx_DMA_Channel,Length); //设置传输长度
	DMA_EnableChannel(USARTz_Tx_DMA_Channel, ENABLE);     //使能DMA通道
#else
    int i;
    for(i = 0; i < len; i++)
	{
		USART_SendData(USARTz, (uint8_t)*(p_buff + i));
		 while (USART_GetFlagStatus(USARTz, USART_FLAG_TXDE) == RESET)
        ;
	}
#endif


}



/**
 * @brief  Configures the different system clocks.
 */
void my_uart_rcc_cfg(void)
{

    /* DMA clock enable */
    RCC_EnableAHBPeriphClk(RCC_AHB_PERIPH_DMA, ENABLE);
#if UART_PRINT_EN
    /* Enable GPIO clock */
    RCC_EnableAPB2PeriphClk(USARTz_GPIO_CLK, ENABLE);
    USARTz_APBxClkCmd(USARTz_CLK, ENABLE);
    /* Enable USARTy and USARTz Clock */
#ifdef USARTy 
    RCC_EnableAPB2PeriphClk(USARTy_GPIO_CLK, ENABLE);
    USARTy_APBxClkCmd(USARTy_CLK, ENABLE);
#endif
   
#endif 
}


/**
 * @brief  Configures the different GPIO ports.
 */
void uart_gpio_cfg(void)
{
#if UART_PRINT_EN
    GPIO_InitType GPIO_InitStructure;

    /* Initialize GPIO_InitStructure */
    GPIO_InitStruct(&GPIO_InitStructure);

    /* Configure USARTy Tx as alternate function push-pull */
#ifdef USARTy 
    GPIO_InitStructure.Pin            = USARTy_TxPin;    
    GPIO_InitStructure.GPIO_Mode      = GPIO_Mode_AF_PP;
    GPIO_InitStructure.GPIO_Alternate = USARTy_Tx_GPIO_AF;
    GPIO_InitPeripheral(USARTy_GPIO, &GPIO_InitStructure);

    /* Configure USARTy Rx as alternate function push-pull and pull-up */
    GPIO_InitStructure.Pin            = USARTy_RxPin;
    GPIO_InitStructure.GPIO_Pull      = GPIO_Pull_Up;
    GPIO_InitStructure.GPIO_Alternate = USARTy_Rx_GPIO_AF;
    GPIO_InitPeripheral(USARTy_GPIO, &GPIO_InitStructure);    
#endif
	//================================================================//
	    /* Configure USARTz Tx as alternate function push-pull */
    GPIO_InitStructure.Pin            = USARTz_TxPin;
    GPIO_InitStructure.GPIO_Mode      = GPIO_Mode_AF_PP;
    GPIO_InitStructure.GPIO_Alternate = USARTz_Tx_GPIO_AF;
    GPIO_InitPeripheral(USARTz_GPIO, &GPIO_InitStructure);
		
    /* Configure USARTz Rx as alternate function push-pull and pull-up */
    GPIO_InitStructure.Pin            = USARTz_RxPin;
    GPIO_InitStructure.GPIO_Pull      = GPIO_Pull_Up;
    GPIO_InitStructure.GPIO_Alternate = USARTz_Rx_GPIO_AF;
    GPIO_InitPeripheral(USARTz_GPIO, &GPIO_InitStructure);   
#endif    
}

/**
 * @brief  Configures the nested vectored interrupt controller.
 */
static void uart_nvic_cfg(void)
{
    NVIC_InitType NVIC_InitStructure;

    /* Configure the NVIC Preemption Priority Bits */
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);

    /* Enable the USARTy Interrupt */
#ifdef USARTy 
    NVIC_InitStructure.NVIC_IRQChannel            = USARTy_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelCmd         = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
#endif
    // /* Enable the USARTz Interrupt */
    // NVIC_InitStructure.NVIC_IRQChannel            = USARTz_IRQn;
    // NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
    // NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
    // NVIC_InitStructure.NVIC_IRQChannelCmd         = ENABLE;
    // NVIC_Init(&NVIC_InitStructure);
}




void my_uart_cfg(void)
{
#if UART_PRINT_EN
    /* USARTy and USARTz configuration ------------------------------------------------------*/
    USART_StructInit(&USART_InitStructure);
    USART_InitStructure.BaudRate            = 115200;
    USART_InitStructure.WordLength          = USART_WL_8B;
    USART_InitStructure.StopBits            = USART_STPB_1;
    USART_InitStructure.Parity              = USART_PE_NO;
    USART_InitStructure.HardwareFlowControl = USART_HFCTRL_NONE;
    USART_InitStructure.Mode                = USART_MODE_RX | USART_MODE_TX;

    /* Configure USARTy and USARTz */
#ifdef USARTy   
    USART_Init(USARTy, &USART_InitStructure);
#endif    
    USART_Init(USARTz, &USART_InitStructure);

    /* Enable USARTy Receive and Transmit interrupts */
#ifdef USARTy     
    USART_ConfigInt(USARTy, USART_INT_RXDNE, ENABLE);
    USART_ConfigInt(USARTy, USART_INT_TXDE, ENABLE);
#endif
    // /* Enable USARTz Receive and Transmit interrupts */
    USART_ConfigInt(USARTz, USART_INT_RXDNE, ENABLE);
    // USART_ConfigInt(USARTz, USART_INT_TXDE, ENABLE);

#ifdef UART_USE_DMA
    /* Enable USARTz DMA Rx and TX request */
    USART_EnableDMA(USARTz, USART_DMAREQ_RX | USART_DMAREQ_TX, ENABLE);

    /* Enable USARTz TX DMA Channel */
    DMA_EnableChannel(USARTz_Tx_DMA_Channel, ENABLE);
    /* Enable USARTz RX DMA Channel */
    DMA_EnableChannel(USARTz_Rx_DMA_Channel, ENABLE);
#endif

    /* Enable the USARTy and USARTz */
#ifdef USARTy    
    USART_Enable(USARTy, ENABLE);
#endif    
    USART_Enable(USARTz, ENABLE);

#ifdef UART_USE_DMA
	/* 使能USART与DMA */
	USART_EnableDMA(USARTz, USART_DMAREQ_RX | USART_DMAREQ_TX, ENABLE);
#endif
	/* 使能USART空闲中断*/
	USART_ConfigInt(USARTz, USART_INT_IDLEF, ENABLE);
	USART_Enable(USARTz, ENABLE);			//使能USART	
	// /*配置中断*/
	// NVIC_InitStructure.NVIC_IRQChannel                   = USARTz_IRQn;
	// NVIC_InitStructure.NVIC_IRQChannelPriority           = 0;
	// NVIC_InitStructure.NVIC_IRQChannelCmd                = ENABLE;
	// NVIC_Init(&NVIC_InitStructure);

#endif  
}

/* retarget the C library printf function to the USART */
int fputc(int ch, FILE* f)
{
#if UART_PRINT_EN
#ifdef USARTy 
    USART_SendData(USARTx, (uint8_t)ch);
    while (USART_GetFlagStatus(USARTx, USART_FLAG_TXDE) == RESET)
        ;
#endif
     USART_SendData(USARTz, (uint8_t)ch);
     while (USART_GetFlagStatus(USARTz, USART_FLAG_TXDE) == RESET)
         ;

    return (ch);
#endif    
}

void uart_send(uint8_t *p_data, uint8_t len)
{
#if UART_PRINT_EN
			
	uint8_t i;
#ifdef USARTy     
	for(i = 0; i < len; i++)
	{
		USART_SendData(USARTx, (uint8_t)*(p_data + i));
		 while (USART_GetFlagStatus(USARTx, USART_FLAG_TXDE) == RESET)
        ;
	}
#endif

	for(i = 0; i < len; i++){
		USART_SendData(USARTz, (uint8_t)*(p_data + i));
		while (USART_GetFlagStatus(USARTz, USART_FLAG_TXDE) == RESET)
        ;
	}

#endif    
}

void my_uart_init(void)
{   
    my_uart_rcc_cfg();
    uart_nvic_cfg();
    uart_gpio_cfg();
    my_uart_cfg();
}
